//
//  KKHttpServices.m
//  BurNing
//
//  Created by LIKUN on 15/8/13.
//  Copyright (c) 2015年 LIKUN. All rights reserved.
//

#import "KKHttpServices.h"

static KKHttpServices *httpServices = nil;

@implementation KKHttpServices
+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpServices = [[KKHttpServices alloc]init];
    });
    return httpServices;
}

+(NSMutableURLRequest *)getMutableURLRequest:(HttpType)type url:(NSString*) url
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setTimeoutInterval:TimeOut];
    if (type == HttpTypeGet) {
        [request setHTTPMethod:@"GET"];
    }else{
        [request setHTTPMethod:@"POST"];
    }
    return request;
}
/**
 *  解析Http返回
 *
 *  @param operation http返回对象
 *
 *  @return 解析的KKHttpParse对象
 */
+ (KKHttpParse *)parseResponse:(AFHTTPRequestOperation *)operation
{
    NSString* responseStr = operation.responseString;
    NSMutableDictionary* jsonDic = nil;
    if (responseStr.length > 0) {
        jsonDic = [NSJSONSerialization JSONObjectWithData:[responseStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
    }else
        return nil;
    
    KKHttpParse *parse = [[KKHttpParse alloc]init];
    parse.responseCode = operation.response.statusCode;
    parse.responseMsg = operation.response.description;
    parse.responseJsonOB = jsonDic;
    return parse;
}
/**
 *  http请求
 *
 *  @param url          url
 *  @param succsssBlock 成功的回调
 *  @param failureBlock 失败的回调
 *
 *  @return http请求对象
 */
+ (AFHTTPRequestOperation *)httpNetworkWithUrl:(NSString *)url prams:(NSDictionary *)prams success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = NoNetworkState;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
        return nil;
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"operation.str == %@",operation.responseString);
        KKHttpParse *parse = [KKHttpServices parseResponse:operation];
        if (parse) {
            succsssBlock(operation,parse);
        }else{
            failureBlock(parse);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = operation.response.statusCode;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }];
    [[[KKHttpServices shareInstance]operationQueue]addOperation:operation];
    return operation;
}

+ (void)httpPostUrl:(NSString *)url prams:(NSDictionary *)dic success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
             cancel:(KKCancelBlock)cancelBlock{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = NoNetworkState;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager]POST:url parameters:dic success:^(AFHTTPRequestOperation * operation, id responseObject) {
        NSLog(@"operation.str == %@",operation.responseString);
        KKHttpParse *parse = [KKHttpServices parseResponse:operation];
        if (parse) {
            if ([parse.responseJsonOB[@"status"] intValue] == 1) {
                succsssBlock(operation,parse);
            }else{
                //逻辑错误
                [[self class]setFilter:parse];
                failureBlock(parse);
            }
        }else{
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }

    } failure:^(AFHTTPRequestOperation * operation,  NSError *error) {
        KKHttpParse *parse = [[self class]setErrorFilter];
        failureBlock(parse);
    }];
    
    cancelBlock(operation);
}
+ (void)setFilter:(KKHttpParse *)parse
{
    NSString *msg = parse.responseJsonOB[@"message"];
    [parse.responseHead setValue:msg forKey:@"message"];
}
+ (KKHttpParse *)setErrorFilter
{
    KKHttpParse* a = [[KKHttpParse alloc] init];
    a.responseCode = 1000;
    a.responseMsg = MESSAGE_NoNetwork;
    [a.responseHead setValue:MESSAGE_NoNetwork forKey:@"message"];
    return a;
}
#pragma mark 创建建网络错误
+(NSString *) creatHttpErr:(KKHttpParse*) param err:(NSError**)err
{
    if (err != NULL)
    {
        *err = [[NSError alloc] initWithDomain:@"" code:param.responseCode  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[param.responseHead objectForKey:@"message"],@"msg", nil]];
    }
    return nil;
}
+ (void)httpPostUrl:(NSString *)url prams:(NSDictionary *)dic success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = NoNetworkState;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }
    [[AFHTTPRequestOperationManager manager]POST:url parameters:dic success:^(AFHTTPRequestOperation * operation, id responseObject) {
        NSLog(@"operation.str == %@",operation.responseString);
        KKHttpParse *parse = [KKHttpServices parseResponse:operation];
        if (parse) {
            if ([parse.responseJsonOB[@"status"] intValue] == 1) {
                succsssBlock(operation,parse);
            }else{
                //逻辑错误
                [[self class]setFilter:parse];
                failureBlock(parse);
            }
        }else{
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }
        
    } failure:^(AFHTTPRequestOperation * operation,  NSError *error) {
        KKHttpParse *parse = [[self class]setErrorFilter];
        failureBlock(parse);
    }];
}
#pragma mark --- 接口参数加入版本号code验证
+ (void)httpAppPostUrl:(NSString *)url prams:(NSString *)dic code:(NSString *)code success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
             cancel:(KKCancelBlock)cancelBlock{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = NoNetworkState;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }
    NSDictionary *postDic = [NSDictionary dictionaryWithObjectsAndKeys:AppVersion,@"version",@"",@"sign",dic,@"content",code,@"code", nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager]POST:url parameters:postDic success:^(AFHTTPRequestOperation * operation, id responseObject) {
        NSLog(@"operation.str == %@",operation.responseString);
        KKHttpParse *parse = [KKHttpServices parseResponse:operation];
        if (parse) {
            if ([parse.responseJsonOB[@"status"] intValue] == 1) {
                succsssBlock(operation,parse);
            }else{
                //逻辑错误
                [[self class]setFilter:parse];
                failureBlock(parse);
            }
        }else{
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }
        
    } failure:^(AFHTTPRequestOperation * operation,  NSError *error) {
        KKHttpParse *parse = [[self class]setErrorFilter];
        failureBlock(parse);
    }];
    
    cancelBlock(operation);
}


+ (void)postUploadFile:(NSData *)originalImage oriName:(NSString *)oriname thumbnail:(NSData *)tdata thumname:(NSString *)thumname success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
                cancel:(KKCancelBlock)cancelBlock
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *url = [NSString stringWithFormat:@"%@imgUpload",ServerURL];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:originalImage name:@"img" fileName:oriname mimeType:@"image/png"];
        [formData appendPartWithFileData:tdata name:@"img_small" fileName:thumname mimeType:@"image/png"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"operation.str == %@",operation.responseString);
        KKHttpParse *parse = [KKHttpServices parseResponse:operation];
        if (parse) {
            if ([parse.responseJsonOB[@"status"] intValue] == 1) {
                succsssBlock(operation,parse);
            }else{
                //逻辑错误
                [[self class]setFilter:parse];
                failureBlock(parse);
            }
        }else{
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        KKHttpParse *parse = [[self class]setErrorFilter];
        failureBlock(parse);
    }];
    
}
@end
